package com.kedou.app;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.kedou.util.GetImagePath;
import com.kedou.util.ImageTools;

/**
 * 上传名片 界面
 * 
 * @author zhouchao
 * 
 */
public class BusinessCardActivity extends BaseActivity implements
		OnClickListener {
	/**
	 * 下一步 Textview
	 */
	private TextView mTvNext;
	/**
	 * 拍照
	 */
	private ImageView mImgTakeBusinessCard;
	/**
	 * 名片处
	 */
	private ImageView mImgBusinessCard;
	private static final int TAKE_PICTURE = 0;
	private static final int CHOOSE_PICTURE = 1;
	private static final int CROP = 2;
	private static final int CROP_PICTURE = 3;

	private static final int SCALE = 4;// 照片缩小比例
	private String picPath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_businesscard);
		setTitle(R.string.title_of_registinvestor);
		initView();
		setListener();
	}

	/**
	 * 初始化布局
	 */
	private void initView() {
		mTvNext = (TextView) findViewById(R.id.tv_next);
		mImgTakeBusinessCard = (ImageView) findViewById(R.id.img_takebusinesscard);
		mImgBusinessCard = (ImageView) findViewById(R.id.img_businesscard);
	}

	/**
	 * 设置监听器
	 */
	private void setListener() {
		mTvNext.setOnClickListener(this);
		mImgTakeBusinessCard.setOnClickListener(this);
	}

	/**
	 * 点击事件
	 * 
	 * @param v
	 *            布局
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_next:
			Intent intent = new Intent(this, RegistionSubmitActivity.class);
			this.startActivity(intent);
			break;
		case R.id.img_takebusinesscard:
			showPicturePicker(BusinessCardActivity.this);
			break;
		}
	}

	/**
	 * 弹出选择对话框，拍照or相册
	 * 
	 * @param context
	 */
	public void showPicturePicker(Context context) {
		AlertDialog.Builder builder = new AlertDialog.Builder(context);
		builder.setTitle(getResources().getString(R.string.img_source));
		builder.setNegativeButton(getResources().getString(R.string.cancel),
				null);
		builder.setItems(
				new String[] { getResources().getString(R.string.take_photo),
						getResources().getString(R.string.album) },
				new DialogInterface.OnClickListener() {
					// 类型码
					int REQUEST_CODE;

					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case TAKE_PICTURE:
							Intent openCameraIntent = new Intent(
									MediaStore.ACTION_IMAGE_CAPTURE);
							REQUEST_CODE = TAKE_PICTURE;
							// id_image.jpg为一个临时文件，每次拍照后这个图片都会被替换
							String fileName = "card_image.jpg";
							Uri imageUri = Uri.fromFile(new File(Environment
									.getExternalStorageDirectory(), fileName));
							// 指定照片保存路径（SD卡），
							openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
									imageUri);
							startActivityForResult(openCameraIntent,
									REQUEST_CODE);
							break;
						case CHOOSE_PICTURE:
							Intent openAlbumIntent = new Intent(
									Intent.ACTION_GET_CONTENT);
							REQUEST_CODE = CHOOSE_PICTURE;
							openAlbumIntent
									.setDataAndType(
											MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
											"image/*");
							startActivityForResult(openAlbumIntent,
									REQUEST_CODE);
							break;
						default:
							break;
						}
					}
				});
		builder.create().show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		mImgBusinessCard.setVisibility(View.VISIBLE);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {

			case TAKE_PICTURE:
				// 将保存在本地的图片取出并缩小后显示在界面上
				picPath = Environment.getExternalStorageDirectory()
						+ "/card_image.jpg";
				Bitmap bitmap = BitmapFactory.decodeFile(picPath);
				Bitmap newBitmap = ImageTools.zoomBitmap(bitmap,
						bitmap.getWidth() / SCALE, bitmap.getHeight() / SCALE);
				// 由于Bitmap内存占用较大，这里需要回收内存，否则会报out of memory异常
				bitmap.recycle();
				// 将处理过的图片显示在界面上，并保存到本地
				mImgBusinessCard.setImageBitmap(newBitmap);
				ImageTools.savePhotoToSDCard(newBitmap, Environment
						.getExternalStorageDirectory().getAbsolutePath(),
						String.valueOf(System.currentTimeMillis()));
				break;
			case CHOOSE_PICTURE:
				ContentResolver resolver = getContentResolver();
				// 照片的原始资源地址
				Uri originalUri = data.getData();
				try {
					// 使用ContentProvider通过URI获取原始图片
					Bitmap photo = MediaStore.Images.Media.getBitmap(resolver,
							originalUri);
					if (photo != null) {
						String path = GetImagePath.getPath(
								BusinessCardActivity.this, originalUri);
						if (path.endsWith(".jpg") || path.endsWith(".png")) {
							picPath = path;
							// 为防止原始图片过大导致内存溢出，这里先缩小原图显示，然后释放原始Bitmap占用的内存
							Bitmap smallBitmap = ImageTools.zoomBitmap(photo,
									photo.getWidth() / SCALE, photo.getHeight()
											/ SCALE);
							// 释放原始图片占用的内存，防止out of memory异常发生
							photo.recycle();
							mImgBusinessCard.setImageBitmap(smallBitmap);
						} else {
							Toast.makeText(BusinessCardActivity.this,
									getResources()
											.getString(R.string.not_image),
									Toast.LENGTH_SHORT);
						}
					}
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;

			}
			System.out.println("card: " + picPath);
		}
	}
}
